CosmosDB is a globally distributed database which can be used to build highly scalable and reliable applications. It supports document, key-value, wide-column, and graph databases. CosmosDB is a schema-free database. Developers don’t need to worry about the schema of the database. Another cool feature is index management. It automatically indexes the data. It supports Multi-API for accessing the data. Users can access the data using SQL, Gremlin, Cassandra, Table, and MongoDB APIs. Pricing is based on data storage and throughput. Throughput can be changed dynamically also which is another advantage of CosmosDB. Dynamic throughput can be used to reduce costs.
Demo Time:
Now without wasting our time, let’s jump into the azure portal and start playing with CosmosDB.
1. Open Azure Portal and create a new resource
2. From the menu select Azure Cosmos DB
3. Enter the basic setting into the page and press Review+Create
https://www.dropbox.com/s/spk123qte9bjmt3/Screen Shot 2019-11-28 at 8.17.48 PM.png?dl=0
Now let’s create a container and collection and start putting data into it.
1. Open the created CosmosDB database and go to Data Explorer
2. Now click on New Container. Inside the popup fill all the details like database id, throughput, partition key, etc. and press OK. Later we’ll see how we can dynamically change the throughput.
3. Now inside the created database, you can see a container. Expand it and click on Items, then New Item.
4. Inside it create a JSON object
1 2 3 4 5 6
{ "id": "1", "category": "development", "name": "blog", "description": "Lorem ipsum" }
5. Save the document. Now you can see it inside __Items__.
Now let’s try to create containers and documents using Python SQL API.
P.S. For this while creating the CosmosDB account we need to select SQL API in the basic settings page.
First, we need to install Azure Cosmos DB SQL API client library for Pythonpip install azure-cosmos
Now get the Endpoint URI and Primary Key for the database. For that open the cosmos DB account in the Azure portal and go to QuickStart.
Import cosmos_client from the Python SQL libraryimport azure.cosmos.cosmos_client as cosmos_client
Now initialize the cosmos client
1 2 3 4 5 6 7 8 9 10
config = { 'ENDPOINT': 'https://YOUR_DB_NAME.documents.azure.com:443/', 'PRIMARYKEY': 'PRIMARY_KEY', 'DATABASE': 'CosmosDatabase' } # Initialize the Cosmos client client = cosmos_client.CosmosClient(url_connection = config['ENDPOINT'], auth = { 'masterKey': config['PRIMARYKEY'] })
Create a database
1 2 3 4
db = client.CreateDatabase({ 'id': config['DATABASE'] }) db_link = db['_self']
Create a container
1 2 3 4 5 6 7 8 9
options = { 'offerThroughput': 10000 } container_definition = { 'id': collection_name } container = client.CreateContainer(db_link, container_definition, options) coll_link = container['_self']
Create a document in the container
1
2
3
4
5
6
document = {
'id': 1,
'name': 'test_data',
'description': 'Container Item'
}
client.CreateItem(coll_link, document)
Here is the final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import azure.cosmos.cosmos_client as cosmos_client config = { 'ENDPOINT': 'https://YOUR_DB_NAME.documents.azure.com:443/', 'PRIMARYKEY': 'PRIMARY_KEY', 'DATABASE': 'CosmosDatabase' } # Initialize the Cosmos client client = cosmos_client.CosmosClient(url_connection = config['ENDPOINT'], auth = { 'masterKey': config['PRIMARYKEY'] }) #create db try: db = client.CreateDatabase({ 'id': config['DATABASE'] }) db_link = db['_self'] except Exception as e: # if DB is already there db_id = config['DATABASE'] db_query = "select * from r where r.id = '{0}'".format(db_id) db = list(client.QueryDatabases(db_query))[0] db_link = db['_self'] # Create container options options = { 'offerThroughput': 10000 } container_definition = { 'id': collection_name } try: # Create a container container = client.CreateContainer(db_link, container_definition, options) coll_link = container['_self'] except Exception as e: # if collection is already there coll_id = collection_name coll_query = "select * from r where r.id = '{0}'".format(coll_id) coll = list(client.QueryContainers(db_link, coll_query))[0] coll_link = coll['_self'] #insert data document = { 'id': 1, 'name': 'test_data', 'description': 'Container Item' } client.CreateItem(coll_link, document)
I hope you guys liked this post. In our next blog, we’ll go deeper into Azure cosmos DB and try few more techniques. Till then happy coding :)
References: